<template>
    <van-nav-bar
            title="新增收货地址"
            left-arrow
            fixed
            @click-left="$router.go(-1)"
    ></van-nav-bar>

    <van-form @submit="onSubmit" class="form">
        <van-cell-group inset>
            <van-field
                    name="姓名"
                    label="姓名"
                    placeholder="收货人姓名"
                    v-model="form.real_name"
            />
            <van-field
                    name="手机号"
                    label="手机号"
                    placeholder="收货人手机号"
                    v-model="form.phone"
            />
            <van-field
                    v-model="fieldValue"
                    is-link
                    readonly
                    label="地区"
                    placeholder="请选择所在地区"
                    @click="showAreaPopup = true"
            />
            <van-popup v-model:show="showAreaPopup" round position="bottom">
                <van-cascader
                        v-model="cascaderValue"
                        title="请选择所在地区"
                        :options="options"
                        @close="showAreaPopup = false"
                        @finish="onFinish"
                        :field-names="{ text: 'n', value: 'v', children: 'c' }"
                />
            </van-popup>

            <van-field
                    name="详细地址"
                    label="详细地址"
                    placeholder="请填写详细地址"
                    v-model="form.detail"
            />
        </van-cell-group>

        <van-cell-group inset>
            <!--            <van-cell title="设置默认地址" class="set-default">-->
            <!--                <van-switch size="0.5rem"/>-->
            <!--            </van-cell>-->
            <van-field name="switch" label="设置默认地址" input-align="right">
                <template #input>
                    <van-switch size="0.5rem" v-model="form.is_default"/>
                </template>
            </van-field>
        </van-cell-group>

        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit" class="submit-button">
                提交
            </van-button>
        </div>
    </van-form>
</template>

<script setup>
  import { reactive, ref, toRaw, defineProps } from 'vue'
  import { useRouter } from 'vue-router'
  import { addOrEditAddress, getCityList } from '@/api/address.js'
  import { Toast } from 'vant'

  const router = useRouter()
  const { cartIds } = defineProps({ cartIds: String })

  const form = reactive({
    real_name: '',
    phone: '',
    address: {
      id: 0,
      province: '',
      city: '',
      city_id: '',
      district: '',
    },
    detail: '',
    is_default: false,
  })

  const onSubmit = async () => {
    const { status, msg } = await addOrEditAddress(toRaw(form))
    if (status !== 200) {
      return Toast.fail(msg)
    }
    if (cartIds) {
      router.push({
        name: 'order-confirm',
        params: {
          cartIds,
        },
      })
    } else {
      router.push({
        name: 'user',
      })
    }
  }

  // 如果c是空数组，则去掉c属性
  const processAreaData = data => {
    data.forEach(item => {
      // 找到空的 c 属性了，说明 item 是区级信息，组件要求去掉 c
      if (item.c.length === 0) {
        delete item.c
      } else {
        // 说明是省或市，递归处理即可
        processAreaData(item.c)
      }
    })
    return data
  }

  const showAreaPopup = ref(false)
  const fieldValue = ref('')
  const cascaderValue = ref('')
  const options = ref([])
  ;(async () => {
    const { data } = await getCityList()
    options.value = processAreaData(data)
  })()
  // 全部选项选择完毕后，会触发 finish 事件
  const onFinish = ({ selectedOptions }) => {
    showAreaPopup.value = false;
    console.log(selectedOptions)
    fieldValue.value = selectedOptions.map(option => option.n).join('/');
    // 赋值给表单
    form.address.province = selectedOptions[0].n
    form.address.city = selectedOptions[1].n
    form.address.city_id = selectedOptions[1].v
    form.address.district = selectedOptions[2].n
  }
</script>

<style lang="scss" scoped>
    .form {
        margin-top: 46px;
        background-color: #F7F7F7;

        .van-cell-group {
            margin-bottom: 10px;
        }
    }
</style>
